<template>
  <div style="transform: none">
    <headerXX :name="title"></headerXX>
    <van-tree-select
      :main-active-index="activeIndex"
      height="calc(var(--real-vh, 1vh) * 100 - 55px - env(safe-area-inset-bottom) - env(safe-area-inset-top))"
      :items="items"
      :active-id="activeId"
      @click-nav="onClickNav"
    >
      <template #content>
        <van-pull-refresh
          class="pull-refresh"
          v-model="refreshing"
          @refresh="onRefresh"
        >
          <van-empty
            v-if="list.length == 0 && !error"
            image="search"
            description="未找到数据"
          />
          <van-empty v-if="error" image="error" description="网络错误" />
          <van-list
            :immediate-check="false"
            v-model:loading="loading"
            :finished="finished"
            :error.sync="error"
            error-text="请求失败，点击重新加载"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <!-- 列表内容 -->
            <div class="ullist">
              <div
                class="ul"
                v-for="(item, index) in list[activeIndex]"
                :key="index"
              >
                <div class="li">
                  <div class="li_img">
                    <van-image
                      class="img"
                      radius="4"
                      width="70"
                      height="70"
                      :src="item.goodImage"
                      mode=""
                    >
                    </van-image>
                  </div>
                  <div class="li_text">
                    <div class="title WZ_size_14" style="font-weight: 700">
                      {{ item.goodName }}
                    </div>
                    <div class="text_JJ WZ_size_10 example1">
                      {{ item.goodDescription }}
                    </div>

                    <div class="li_D">
                      <div class="Price WZ_size_12" style="color: #ff9900">
                        {{ item.goodPrice }}元
                      </div>
                      <!-- <div class="li_btn" @click="itemClick(item)">
                      领 取
                    </div> -->
                      <div class="li_right__num">
                        <van-stepper
                          class="stepper"
                          v-model="item.goodQty"
                          theme="round"
                          min="0"
                          :default-value="0"
                          @change="valChange(item)"
                          input-width="24px"
                          button-size="18px"
                        />
                      </div>
                    </div>
                  </div>
                </div>
                <van-divider
                  :style="{
                    borderColor: '#999',
                    margin: '5px 0',
                  }"
                >
                </van-divider>
              </div>
            </div>
            <template #error>
              <div class="error-tip" @click="retryLoad">
                <van-icon name="warning" />
                <span>加载失败，点击重试</span>
              </div>
            </template>
          </van-list>
        </van-pull-refresh>
      </template>
    </van-tree-select>
    <div class="DI" style="position: fixed; bottom: 0">
      <div style="font-size: 16px; margin-top: 10px">合计费用：￥{{ ZJG }}</div>
      <van-button
        style="width: 300px; margin-bottom: 20px"
        class="buy"
        color="#36C2A8"
        @click="jumpToBuy()"
        >预 购</van-button
      >
    </div>
    <!-- <van-dialog
    title="共享衣柜"
    :show="imgshow"
    @cancel="imgshow = false"
    @confirm="LQ"
    show-cancel-button
  >
    <div style="text-align: center">
      <van-image width="150px" height="150px" :src="SPxx.goodImage"></van-image>
      <div class="WZ_size_16" style="color: #027571">{{ SPxx.goodName }}</div>
      <div class="WZ_size_14" style="padding: 10px 0">单人单次可领取一剂本药品，是否确认领取？</div>
    </div>
  </van-dialog> -->
  </div>
</template>

<script>
import moment from "moment";
import {
  getSiteCategoryList,
  getClothesList,
} from "@/api/realAssets/icsharedstation/GXYG/index.js";
import { Toast, Dialog } from "vant";
import headerXX from "../../components/title.vue";
import { setgoods, getgoods } from "../../common/SPXX";
import { getAccessToken } from "../../common/YYSLxx.js";
import { testUserMessage } from "../../common/testUser.js";
export default {
  components: {
    headerXX,
  },
  data() {
    return {
      categoryList: [],
      activeIndex: 0,
      clothesList: [],
      imgshow: false,
      title: "共享衣柜",
      activeId: "1",
      siteData: JSON.parse(localStorage.getItem("siteData")) || {},
      loading: false,
      finished: false,
      error: false,
      refreshing: false,
      list: [],
      id: 0,
      items: [],
      SPxx: {},
      ZJG: 0.0,
      XXyz: {
        siteId: "",
        categoryId: 0,
        pageNumber: 1,
        pageSize: 10,
      },
    };
  },
  methods: {
    //点击转到预约
    itemClick(item) {
      this.imgshow = true;
      item.goodManufacturer = "共享衣柜";
      let list = [];
      this.SPxx = item;
      list.push(this.SPxx);
      let li = encodeURIComponent(JSON.stringify(list).replace(/%/g, "%25"));
      //把商品信息存储本地
      setgoods(li);
      //   router.push("/BJFW/choseTime");
    },
    jumpToBuy() {
      if (this.ZJG == 0) {
        Dialog.alert({
          message: "请选择一项商品服务",
        });
        return;
      }
      Dialog.confirm({
        // title: '预定提示',
        message:
          "是否确认预购共享衣柜服务，预订成功后请移步至共享驿站服务台核销服务(支持刷卡/微信/支付宝付款)",
      })
        .then(() => {
          let SPlist = [];
          let itemList = [];
          this.list.forEach((item) => {
            item.forEach((itemm) => {
              if (itemm.goodQty > 0) {
                SPlist.push({
                  id: itemm.goodId,
                  requestQty: itemm.goodQty,
                });
                itemList.push(itemm);
                console.log(itemm);
              }
            });
          });
          const currentTimeStamp = moment().unix();
          const min = BigInt("1" + "0".repeat(18));
          const max = BigInt("1" + "0".repeat(19));
          const randomNum =
            min + BigInt(Math.floor(Math.random() * Number(max - min)));

          let itemXX = {
            SBBT: "共享衣柜",
            orderNumber: currentTimeStamp + randomNum.toString(), //预约编号
            siteId: this.siteData.id, //服务点id
            orderProject: "共享衣柜", //预约项目
            orderProjectType: "0", //0:   1:  (区分健康自测类型与其他类型)
            orderCreationTime: moment().format("YYYY-MM-DD"), //下单时间
            goodInfo: SPlist,
            estimateArrivalTime: "", //服务时间
            estimateArrivalTimeTitle: "",
            estimateSumPrice: 0, //预估费用
            orderSubType: "", //预约类型
            serviceDescription: "", //服务介绍
            orderLocation: "", //预约地址(非空展示)
            serviceTip: "", //温馨提示(非空展示)
            goodSumPrice: "", //总价
            serviceTitleList: ["商品名称", "单价", "数量", "小计"], //服务标题
            goodList: [...itemList], //商品列表
          };
          // console.log(SPlist)
          // console.log(itemXX, "1111")
          getAccessToken(itemXX, "共享衣柜");
        })
        .catch(() => {
          // on cancel
        });
    },
    // 切换左侧分类
    onClickNav(index) {
      this.activeIndex = index;
      this.activeId = this.items[index].id;
      this.id = this.items[index].id;
      this.onRefresh();
    },
    // 下拉刷新
    onRefresh() {
      this.error = false;
      this.refreshing = true;
      this.getinformation();
    },
    // 点击重试
    retryLoad() {
      this.error = false;
      this.getinformation();
    },
    // 获取右边列表
    onLoad() {
      if (this.error) return; // 如果当前是错误状态，不自动触发加载
      // this.XXyz.companyId = this.arrayString.id
      this.XXyz.categoryId = this.id;
      getClothesList(this.XXyz).then((res) => {
        console.log(res.data);
        if (res.resultMessage != "SUCCESS") {
          this.error = true; // 显示错误提示
        } else {
          res.data = res.data.map((item) => {
            return {
              goodName: item.clothesName, // 名称
              goodId: item.id, // id
              goodImage: item.clothesImage, // 图片
              goodPrice: item.clothesPrice, // 价格
              goodClothesAvailable: item.clothesAvailable, // 可用数量
              goodSiteId: item.siteId, // 站点id
              goodCountPrice: 0,
              btn: "领取",
              goodQty: 0,
              requestQty: 0,
            };
          });
          this.list[this.activeIndex] = res.data;
        }
        this.finished = true;
        this.loading = false;
        this.refreshing = false;
      });
    },
    // 获取左边列表
    getinformation() {
      getSiteCategoryList({
        siteId: this.siteData.id,
      }).then((res) => {
        if (res.resultCode == "1" && res.resultMessage == "SUCCESS") {
          this.items = res.data;
          this.categoryList = res.data.map((item) => {
            item.goodName = item.categoryName;
            item.type = item.categoryType;
            item.goodId = item.id;
            return item;
          });
          for (let i = 0; i < res.data.length; i++) {
            this.list.push([]);
          }
          // 默认拿到第一个id
          this.id = this.items[this.activeIndex].id;
          this.items.forEach((item) => {
            item.text = item.categoryName;
          });
          this.onLoad();
        } else {
          Toast.fail("网络错误");
        }
      });
    },
    valChange(e) {
      this.ZJG = 0;
      this.list[this.activeIndex].forEach((item) => {
        if (item.goodId == e.goodId) {
          item.goodQty = e.goodQty;
          item.goodCountPrice = item.goodQty * item.goodPrice;
        }
      });
      this.list.forEach((item) => {
        item.forEach((itemm) => {
          this.ZJG += itemm.goodCountPrice;
        });
      });
    },
  },
  mounted() {
    testUserMessage("共享衣柜").then((siteData) => {
      this.siteData = siteData[0];
      this.XXyz.siteId = siteData[0].id;
      this.getinformation();
    });
  },
};
</script>
<style>
.van-sidebar-item--select:before {
  background-color: rgb(2, 117, 113) !important;
}
.van-stepper__plus {
  background-color: #36c2a8 !important;
}
.van-stepper__minus {
  color: #36c2a8 !important ;
  border: 0.02667rem solid #36c2a8 !important;
}
</style>
<style lang="less">
@import "../../static/css/index.less";
@import "../../static/css/GYcSS.less";
.van-sidebar-item--select:before {
  background-color: rgb(2, 117, 113) !important;
}
.pull-refresh {
  background: #fff;
  height: calc(
    var(--real-vh, 1vh) * 100 - 150px - env(safe-area-inset-bottom) -
      env(safe-area-inset-top)
  );
}
// .pull-refresh {
//   background: #fff;
//   height: calc(
//     var(--real-vh, 1vh) * 100 - 150px - env(safe-area-inset-bottom) - env(safe-area-inset-top)
//   );
// }
// .ullist {
//   margin-bottom: 40px;
// }
.error-tip {
  padding: 16px;
  color: #f56c6c;
  text-align: center;
}
.error-tip .van-icon {
  margin-right: 4px;
  vertical-align: middle;
}
.stepper {
  --van-stepper-background-color: #36c2a8;
  --van-stepper-button-icon-color: #36c2a8;
  --van-stepper-button-disabled-color: #36c2a8;
  --van-stepper-button-disabled-icon-color: #36c2a8;
  --van-stepper-button-round-theme-color: #36c2a8;
  --van-stepper-input-disabled-text-color: #36c2a8;
  --van-stepper-input-disabled-background-color: #36c2a8;
}
</style>
